package com.apimarket.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

/**
 * @Description:访问决策管理器
 * 在里面对当前请求的资源进行权限判断，判断当前登录用户是否拥有该权限，如果有就放行，如果没有就抛出一个"权限不足"的异常。
 * @Author ZXR
 * @Date 2021/7/20 20:05
 * @Version 1.0
 */

@Component
public class CustomizeAccessDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        Iterator<ConfigAttribute> iterator=collection.iterator();
        while(iterator.hasNext()){
            ConfigAttribute ca = iterator.next();
            //获取当前请求需要的权限
            String needPermission = ca.getAttribute();
            //获取当前用户所具有的权限
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for(GrantedAuthority authority:authorities){
                if(authority.getAuthority().equals(needPermission)){
                    //只要找到一个，访问当前资源需要拥有的权限，那么就允许访问
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足！");
    }

    //这里需要设置为true，否则会报错
    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    //这里需要设置为true，否则会报错
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
